import { RequestCode, UserAction, packedData } from "../GlobalData/DataStruct";

export default class webSocket extends Laya.Script {
    private socketObj:Laya.Socket;
    constructor() 
    { 
        super(); 
        //1.创建一个Socket对象
        this.socketObj=new Laya.Socket();
        //2.连接服务器
        this.socketObj.connectByUrl("ws://localhost:8888");
        //3.四种状态监听
        this.socketObj.on(Laya.Event.OPEN, this, this.openHandler);
        this.socketObj.on(Laya.Event.MESSAGE, this, this.receiveHandler);
        this.socketObj.on(Laya.Event.CLOSE, this, this.closeHandler);
        this.socketObj.on(Laya.Event.ERROR, this, this.errorHandler);
    }
    



    /**将打包的数据发送到服务端 */
    public sendMsg(packedData:any)
    {
        //发送数据
        this.socketObj.send(packedData)
    }
    /**打包数据 */
    public packData(requestCode:any,actionCode:any,data:any)
    {
        //创建打包数据对象
        let msg_obj=new packedData()
        msg_obj.RequestCode=requestCode
        msg_obj.ActionCode=actionCode
        msg_obj.data=data
        //返回JSON字符串
        return JSON.stringify(msg_obj)
    }
    /**成功建立连接回调 */
    openHandler(){}
    /**收到消息回调 */
    receiveHandler(data:any)
    {
        // console.log(data)
        // return
        let msg=JSON.parse(data);
        switch(msg.RequestCode)
        {
            case RequestCode.USER:
                switch(msg.ActionCode)
                {
                    case UserAction.LOGIN:
                        //TODO:登录操作
                        Laya.stage.event("login",[msg.data])
                        console.log('login')
                        break;
                    case UserAction.SIGNUP:
                        //将消息分发到login_scene
                        Laya.stage.event("register",[msg.data])
                        break;
                    case UserAction.GET_INFO:
                        Laya.stage.event('get_info',[msg.data])
                        break;
                    case UserAction.UPDATE_INFO:
                        Laya.stage.event("updata_info",[msg.data])
                        break;
                }
        }
    }
    /**关闭连接回调 */
    closeHandler(){}
    /**发生错误回调 */
    errorHandler(){}


    onDisable(): void {
    }
}